<?php

namespace App\Logic\Auth;

use App\Const\AdminPermissionConst;
use App\Logic\BaseLogic;
use App\Models\AdminUserModel;
use Illuminate\Support\Facades\Auth;

class WebAuthLogic extends BaseLogic
{
    public function check(?string $route): bool
    {
        if (count($prefix = explode('.', $route)) < 1) {
            return false;
        }

        if (in_array($prefix[0], AdminPermissionConst::ROUTE_NAME_EXCEPT)) {
            return true;
        }

        /** @var AdminUserModel $user */
        $user = Auth::user();
        if (empty($user)) {
            return false;
        }
        if ( in_array($user->id, config('app.super_admin_list')) ) {
            return true;
        }

        $permission_list = $this->getUserPermission($user->id);
        if (in_array($route, $permission_list)) {
            return true;
        }

        return false;
    }

    public function getWebPermission(): array
    {
        $routes = app()->routes->getRoutes();
        $result = [];
        foreach ($routes as $value){
            if ($this->toContinue($value)) {
                continue;
            }
            $result[] = $value->getName();
        }
        return $result;
    }

    private function toContinue($value): bool
    {
        return (
            count($uri_explode = explode('/', $value->uri())) < 1
            ||
            $uri_explode[0] !== AdminPermissionConst::ROUTE_URI_PREFIX_WEB
            ||
            count($route_name_explode = explode('.', $value->getName())) < 2
            ||
            in_array($route_name_explode[0], AdminPermissionConst::ROUTE_NAME_EXCEPT)
        );
    }

    private function getUserPermission($user_id): array
    {
        $list = AdminUserModel::find($user_id)->roles->where('state', 1)->pluck('permission_list');
        $result = [];
        foreach ($list as $val) {
            $result = array_keys(array_flip($val) + array_flip($result));
        }
        return $result;
    }
}
